<?php
$page_title = "编辑用户资料";
include 'template/header.php';

if (isset($_GET["id"]) && is_numeric($_GET["id"])) {
	$id = $_GET["id"];
} else if (isset($_POST["id"]) && is_numeric($_POST["id"])) {
	$id = $_POST["id"];
} else {
	echo '<h1>非法的访问</h1>';
	echo '<p class="error">请不要这样访问此页面。</p>';
	include 'template/footer.php';
	exit();
}

echo '<h1>编辑用户资料</h1>';
require_once 'mysqli_connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$errors = array();
	if (empty($_POST['first_name'])) {
		$errors[] = '未输入名字';
	} else {
		$fn = mysqli_real_escape_string($dbc, $_POST['first_name']);
	}
	if (empty($_POST['last_name'])) {
		$errors[] = '未输入姓氏';
	} else {
		$ln = mysqli_real_escape_string($dbc, $_POST['last_name']);
	}
	if (empty($_POST['email'])) {
		$errors[] = '未输入邮箱';
	} else {
		$em = mysqli_real_escape_string($dbc, $_POST['email']);
	}
	if (empty($errors)) {
		$q = "SELECT user_id FROM users WHERE
			  email='$em' AND user_id != $id";
		$r = @mysqli_query($dbc, $q);
		if (mysqli_num_rows($r) == 0) {
			$q = "UPDATE users SET first_name='$fn', last_name='$ln', email='$em'
				WHERE user_id=$id LIMIT 1";
			$r = @mysqli_query($dbc, $q);
			$af = mysqli_affected_rows($dbc);
			if ($af == 1) {
				echo '<p>编辑成功！</p>';
			} else if ($af == 0){
				echo '<p>未进行任何编辑。</p>';
			} else {
				echo '<h1>系统错误</h1>';
				echo '<p class="error">编辑出现异常。</p>';
				echo '<br /><br />指令：'."$q";
			}
		} else {
			// 同样的 email 已经存在
			echo '<p class="error">同样的 Email 已经存在，请重新修改。</p>';
		}
	} else {
		echo "<h1>填写信息不正确</h1>";
		echo '<p class="error">发生了以下错误：</p>';
		foreach ($errors as $e) {
			echo ' - '.$e.'<br />';
		}
		echo "<br />请重试。";
	}
} else {
	$q = "SELECT first_name, last_name, email FROM users WHERE user_id=$id";
	$r = @mysqli_query($dbc, $q);
	if (mysqli_num_rows($r) == 1) {
		$row = mysqli_fetch_row($r);
		echo '<form action="edit_user.php" method="post">
				<p>名：<input type="text" name="first_name" size="15" maxlength="20"
				value="'.$row[0].'" /></p>
				<p>姓：<input type="text" name="last_name" size="15" maxlength="40"
				value="'.$row[1].'" /></p>
				<p>电子邮箱：<input type="text" name="email" size="20" maxlength="60"
				value="'.$row[2].'" /></p>
				<p><input type="submit" name="submit" value="提交" /></p>
				<input type="hidden" name="id" value="'.$id.'" /></form>';
	} else {
		echo '<h1>系统错误</h1>';
		echo '<p class="error">无法编辑该用户。</p>';
		echo '<br /><br />指令：'."$q";
	}
}


include 'template/footer.php';
?>